<template>
	<view>
		<view :style="{'height':soundState?'':0}" class="mark"></view>
		<view @click="toggleState" class="sound-buttom" :class="{soundState}">
			<!-- <view v-if="soundProgress" class="sound-progress" :style="{'width':soundProgress}"></view> -->
			<view class="title" v-if="soundState">
				语音录入
			</view>
			<image class="voice-play" v-if="soundState" :src="voicePlayImg"></image>
			<text class="sound-text" v-if="soundState">{{'录音中（'+time+'s）'}}</text>
			<image v-else :src="icon"></image>
			
			
			<view class="sound-lan" v-if="soundState">
				语言：<view v-for="lan of lans" :key="lan.id" :style="{color:lan.id===lanId ? '#C4171E':'#000000'}" @click="lanId=lan.id">{{lan.text}}</view>
			</view>
			
			<view class="sound-tip" v-if="soundState">
				<text class="sound-tip-text" :style="{color:cancel?'#f70000':'#000000'}">{{cancel?'松手取消':'点击发送'}}</text>
				<!-- 				<view class="closeIcon" :style="{'background-color':cancel?'#f70000':'#EEEEEE'}">
					<uni-im-icons code="e61a" size="10px" color="#FFFFFF"></uni-im-icons>
				</view>
 -->
			</view>
		</view>
	</view>
</template>

<script>
	// #ifndef H5
	const recorderManager = uni.getRecorderManager();
	// #endif


	let soundInterval, soundPath, startTime;
	const windowInfo = uni.getWindowInfo()
	export default {
		name: 'ZgjSound',
		emits: ['success', 'remove'],
		props: {
			remove: {
				type: Boolean,
				default () {
					return false
				}
			}
		},
		data() {
			return {
				voicePlayImg: 'https://env-00jxhjo1f70q.normal.cloudstatic.cn/1742720638129_0.png?expire_at=1742721239&er_sign=d10b0223478e26e67b1678d17df8dd19',
				soundState: 0,
				soundProgress: 0,
				cancel: false,
				time: 0,
				lanId:0,
				systemInfo: {
					safeAreaInsets: {
						bottom: 0
					}
				},
				lans:[{
					id:0,
					text:'普通话'
				},{
					id:1637,
					text:'粤语'
				}]
			}
		},
		computed: {
			icon() {
				return this.remove ? 'https://env-00jxhjo1f70q.normal.cloudstatic.cn/1742720611651_0.png?expire_at=1742721212&er_sign=090cd96836e487c878b790a8cffcf352' : 'https://env-00jxhjo1f70q.normal.cloudstatic.cn/1742720576216_0.png?expire_at=1742721177&er_sign=5b89d7ec431eb465e4bc10cc29a40e96'
			}
		},
		created() {
			this.systemInfo = uni.getSystemInfoSync()
			let lan=uni.getStorageSync("voice_lan")
			if(lan){
				this.lanId = lan
			}
			else{
				this.lanId = this.$config.voice
			}
			// #ifndef H5
			recorderManager.onStop((res) => {
				console.log('recorderManager.onStop', res, this.cancel);
				// if(!this.cancel){
				if (this.time < 1) {
					return uni.showToast({
						title: '语音时间过短',
						icon: 'none'
					});
				}
				uni.showLoading({
					title: '语音上传中',
					mask: false,
					complete: () => {
						uniCloud.uploadFile({
							filePath: res.tempFilePath,
							cloudPath: 'uni-im/' + uni.getDeviceInfo().deviceId + '/sound/' +
								Date.now() + '.mp3',
							// fileType:"audio",
							success: (e) => {
								console.log('uniCloud.uploadFile-success', e, 'success', {
									"url": e.fileID,
									time: this.time
								});
								try {
									uni.setStorage({
										key:'voice_lan',
										data:this.lanId
									})
									let voiceFile = e.fileID.replace("cloud://env-00jxhjo1f70q","https://env-00jxhjo1f70q.normal.cloudstatic.cn")
									console.log('voicefile:',voiceFile)
									this.$emit('success', {
										"url": voiceFile,
										time: this.time,
										lan:this.lanId
									})
								} catch (e) {
									console.log(e);
									//TODO handle the exception
								}
								uni.hideLoading()
							},
							fail: (e) => {
								console.log(e);
								uni.showModal({
									content: JSON.stringify(e),
									showCancel: false,
									confirmText: '知道了'
								});
							},
							complete: (e) => {
								console.log('complete', e);
								uni.hideLoading()
							}
						})
					}
				});

				// 	}else{
				// 		console.log('用户取消了录音功能','this.time:'+this.time);
				// 	}
			});

			recorderManager.onStart(e => {
				this.cancel = false
				// console.log(e);
			})
			recorderManager.onPause(e => {
				// console.log(e);
			})
			recorderManager.onError(e => {
				console.error(e);
			})
			// #endif
		},
		methods: {
			touchmove(e) {
				let y = (e.touches[0].screenY - windowInfo.screenTop) || e.touches[0].clientY
				if (windowInfo.windowHeight - y > 50) {
					this.cancel = true
				} else {
					this.cancel = false
				}
			},
			toggleState() {
				if (this.remove) {
					this.$emit('remove')
					return
				}
				if (this.soundState === 0) {
					this.soundStart()
				} else {
					this.soundEnd()
				}
			},
			soundStart(e) {
				// 关闭正在播放的sound
				this.time = 0

				// #ifdef H5
				// 防止H5端 调试出现鼠标右键菜单
				window.oncontextmenu = function() {
					return false;
				}
				// #endif

				// #ifdef H5
				// return uni.showToast({
				// 	title: 'h5端不支持语音功能',
				// 	icon: 'none'
				// });
				// #endif

				// #ifndef H5
				recorderManager.start({
					sampleRate: 16000,
					numberOfChannels: 1,
					format: "aac"
				});
				// #endif

				startTime = Date.now()

				console.log('soundStart');

				//进度条
				this.soundState = 1
				soundInterval = setInterval(() => {
					this.soundProgress = parseInt(this.soundProgress) + uni.upx2px(450 / 60) + 'px'
					// console.log('this.soundProgress',this.soundProgress);
					this.time = parseInt((Date.now() - startTime) / 1000)
				}, 1000)
				// e.preventDefault();
			},
			soundEnd() {
				// #ifndef H5
				recorderManager.stop();
				// #endif
				console.log('soundEnd');
				clearInterval(soundInterval)
				setTimeout(() => {
					this.soundState = 0
					this.soundProgress = 0
					this.cancel = false
				}, 300);
			}
		}
	}
</script>

<style lang="scss">
	.sound-buttom {
	background-color: #ffffff;
    padding: 0 40rpx;
    width: 100%;
    height: 46px;
    position: absolute;
    bottom: 0px;
    left: 0px;
    box-sizing: border-box;
    font-size: 16px;
    align-items: center;
    justify-content: center;
    text-align: center;
    z-index: 998;
    overflow: hidden;

		image {
			width: 40px;
			height: 40px;
		}
	}
	
	.title {
		font-size: 30rpx;
		text-align: center;
		padding-top: 25rpx;
		padding-bottom: 55rpx;
	}
	
	.voice-play {
		width: 65rpx;
		height: 70rpx;
	}

	.sound-text {
		position: relative;
		left: -20rpx;
		width: 450rpx;
		font-size: 14px;
		text-align: center;
	}

	.sound-tip {
		width: 260rpx;
		height: 76rpx;
		border-radius: 45rpx;
		background: #FFFFFF;
		border: 1px solid #C4C4C4;
		display: flex;
		text-align: center;
		justify-content: center;
		align-items: center;
	}

	.sound-tip-text {
		color: #999999;
		font-size: 14px;
	}
	.sound-lan{
		z-index: 998;
		display: flex;
		flex-direction: row;
		font-size: 28rpx;
		gap: 20px;
	}

	.closeIcon {
		width: 30px;
		height: 30px;
		background-color: #DDDDDD;
		border-radius: 100px;
		justify-content: center;
		align-items: center;
	}

	.sound-progress {
		// border-radius: 10px;
		height: 44px;
		position: absolute;
		left: 0;
		top: 0;
		padding: 0;
		transition: width 0.2s linear;
		background-color: #2faf4c;
		opacity: 0.3;
	}

	.soundState {
		width: 710rpx;
		height: 538rpx;
		opacity: 1;
		border-radius: 41.67px;
		background: #FFFFFF;
		display: flex;
		flex-direction: column;
		gap: 40rpx;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.mark {
		width: 750rpx;
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0px;
		right: 0;
		background: rgba(0, 0, 0, 0.7);
		flex: 1;
		z-index: 997;
	}
</style>